<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>04列表排序</title>
  <script src="../js/vue.js"></script>
</head>
<body>
  <div id="app">
    <h1>{{title}}</h1>
    <input type="text" placeholder="请输入名字" v-model="keyword">
    <button @click="flag = 2">升序</button>
    <button @click="flag = 1">降序</button>
    <button @click="flag = 0">原序</button>
    <ul>
      <li v-for="p in filterPersons">{{p.name}}-{{p.age}}</li>
    </ul>
  </div>
  <script>
    new Vue({
      el: '#app',
      data(){
        return {
          title: '列表排序',
          persons: [
            {
              id: '001',
              name: '马冬梅',
              age: 20
            },
            {
              id: '002',
              name: '周冬雨',
              age: 19
            },
            {
              id: '003',
              name: '周杰伦',
              age: 18
            },
            {
              id: '004',
              name: '温兆伦',
              age: 21
            }
          ],
          keyword: '',
          flag: 0
        }
      },
      computed: {
        filterPersons() {
          // 1先过滤
          let newArr = this.persons.filter(item => item.name.indexOf(this.keyword) !== -1)
          // 2 再排序
          if(this.flag) {
            newArr.sort((p1, p2) => {
              return this.flag === 1 ? p2.age - p1.age : p1.age - p2.age
            })
          }
          // 3 将过滤且排序后的值返回
          return newArr
        }
      }
    })
  </script>
</body>
</html>